/**
 * 风控
 */
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Alert,
	PixelRatio, Image, ScrollView, Animated
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import MethodUtil from '../../../../utils/MethodUtil';
import { GLOBAL } from '../../../../config/global';
import { CREDIT_TYPES } from '../../../../config/definition';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { SpaceBetween } from '../../create/_components/SpaceBetween.js';
import { MorePage } from '../../create/_components/MorePage.js';
import { ApprovalView, RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import { LightBox, StateLightBox } from '../../../../component/Store';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import HTTP from '../../../../utils/http';
import ToastUtil from '../../../../utils/toast';
import { CURRENCY } from '../../../../utils/helper';

const scale = GLOBAL.SCALE;
const sendData = {};

export class RiskManagerApprovelPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		return {
			headerTitle: params.title,
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	requesting;
	constructor(props) {
		super(props);
		this.orderId = props.navigation.state.params.paramsData.orderId;
		this.companyId = props.navigation.state.params.paramsData.companyId;
		this.orderType = props.navigation.state.params.paramsData.orderType;
		this.businessKey = props.navigation.state.params.paramsData.businessKey;
		this.taskId = props.navigation.state.params.paramsData.taskId;
		this.formKey = props.navigation.state.params.paramsData.formKey;
		this.status = props.navigation.state.params.status;
		this.companyName = props.navigation.state.params.paramsData.companyName;
		this.auditResultName = props.navigation.state.params.paramsData.auditResultName;

		this.animateData = {
			basic: {
				start: {   // 初始值
					basicInfoValue: 120,
					itemValue: [100],
					basicInfoText: '展开更多',
					itemText: ['展开更多']
				},
				end: {  // 介素值
					basicInfoValue: 280,
					itemValue: [220],
					basicInfoText: '收起',
					itemText: ['收起']
				}
			},
		}

		this.state = {
			data: {},
			basicInfoAnim: new Animated.Value(this.animateData.basic.start.basicInfoValue),
			itemAnim: [new Animated.Value(this.animateData.basic.start.itemValue[0])],
			basicInfoOnoff: true,
			itemOnoff: [true],
			resultModalVisible: false,
			loaded: false,
			lightBoxVisible: false,
			stateLightBoxData: false,
			itemOnoffValue: ['展开更多']
		}

		this._closeLightBox = this._closeLightBox.bind(this);
		this.stateLightBoxData = {
			onClosePress: this._closeLightBox,
			modalVisible: false,
			title: '',
			rowDataList: [],
		};
		this.lightBoxData = {
			onClosePress: this._closeLightBox,
			modalVisible: false,
			title: '',
			rowDataList: [],
		};
	}

	componentWillMount () {
		this._getDetailData(this.orderId);
	}

	//初始化详情数据
	async _getDetailData (orderId) {
		this.setState({
			loaded: true
		});

		let responseData = await HTTP.POST(API_GENERATE(API.ORDER_DETAIL), {
			orderId,
			queryType: 'ORDER_ALL_INFO',
		});

		this.setState({
			loaded: false
		});

		if (responseData) {
			this.setState({
				data: responseData
			})
		}
	}

	// animatedFn
	_animatedFn = (num, animateObj) => {
		Animated.timing(
			animateObj,
			{
				duration: 300,
				toValue: num
			}
		).start();
	}
	// 基本信息  更多设置
	_onPressFn = (data, objOnoff, type, animateObj, index) => {
		const { itemOnoff } = this.state;
		let curOnoff = [];
		let itemOnoffValue = [];

		if (type + 'Onoff' == 'itemOnoff') {
			itemOnoffValue[index] = !objOnoff ? '展开更多' : '收起';
			this.curOnoff = itemOnoff;
			//index + 1 > this.curOnoff.length 说明当前点击的item还没有加入itemOnoff值，所以objOnoff当前是undefined,这里付一个初始值true
			//curOnoff是点击后的状态，所以这个付一个false
			objOnoff = index + 1 > this.curOnoff.length ? true : objOnoff;
			curOnoff[index] = index + 1 > this.curOnoff.length ? false : !objOnoff;

			this.curOnoff.map((item, i) => {
				curOnoff[i] = index === i ? !objOnoff : item;
			})

			this._animatedFn(objOnoff ? data.end[type + 'Value'][index] : data.start[type + 'Value'][index], animateObj);
		} else {
			this._animatedFn(objOnoff ? data.end[type + 'Value'] : data.start[type + 'Value'], animateObj);
		}

		this.setState({
			basicInfoOnoff: type + 'Onoff' == 'basicInfoOnoff' ? !objOnoff : this.state.basicInfoOnoff,
			itemOnoff: type + 'Onoff' == 'itemOnoff' ? curOnoff : this.state.itemOnoff,
			itemOnoffValue: type + 'Onoff' == 'itemOnoff' ? itemOnoffValue : this.state.itemOnoffValue
		})
	}


	//同意，驳回接口调用
	getApprovalView (totalOrderAmt, beyondCreditAmt, unit, periodType) {
		const { data } = this.state;
		const { orderType, payType } = data;
		//HASLOT 已审批   LOT未审批
		return (this.status && this.status === 'LOT') ? (
			<View style={{ backgroundColor: '#fff' }}>
				{
					CREDIT_TYPES[orderType] && CREDIT_TYPES[orderType][payType] && periodType !== 'L' ?
						<View style={{ backgroundColor: '#fff0b3', padding: 10 * scale }}>
							<Text style={{ color: '#cf8300' }}>本单授信额度：{unit.label + MethodUtil.toThousands((totalOrderAmt || 0)) + unit.text}   超出额度：{unit.label + MethodUtil.toThousands((beyondCreditAmt || 0)) + unit.text}</Text>
						</View> : null
				}
				<ApprovalView agreePress={() => {
					sendData.status = 'PASS';
					Alert.alert('提示', '确定要同意此成交报告吗？', [
						{
							text: '再想想',
						}, {
							text: '确定',
							onPress: () => {
								this._fetchApproval('1');
							}
						}
					]);

				}} refusePress={() => {
					this.setState({
						refuseModalVisible: true
					})
				}} />
			</View>
		) : null;
	}

	async _fetchApproval (numStr) {
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.ORDER_TASTK_APPROVAL), {
			businessKey: this.businessKey,
			taskId: this.taskId,
			formKey: this.formKey,
			auditResult: numStr,
			remark: this.remark, // 填写
		});

		this.setState({
			loaded: false
		});
		if (responseData) {
			ToastUtil.showSuccess((numStr == '0') ? '驳回成功' : '审批成功').then(() => { this._goBack(); })
		} else {
			this.requesting = false;
		}
	}

	// 返回上一个页面
	_goBack = () => {
		setTimeout(() => {
			this.requesting = false;
		}, 1000)
		this.props.navigation.goBack();
	}

	//审批节点
	async	_didPressShowStateLightBox (orderId, processInstanceId) {
		this.setState({
			loaded: true
		});
		//查询审批节点
		let responseData1 = await HTTP.GET(API_GENERATE(API.APPROVAL_NODE) + '?bizId=' + orderId + '&bizObjType=1');
		this.setState({
			loaded: false
		});

		this.stateLightBoxData.modalVisible = true;
		this.stateLightBoxData.title = '审批状态';
		this.stateLightBoxData.rowDataList = responseData1.map((item, index) => {
			return {
				taskName: item.taskName,// + '(' + item.auditStaffName + ')',//auditStaffName
				auditTime: item.auditTime,
				auditResult: item.auditResult,
				remark: item.remark,
				auditStaffName: item.auditStaffName,
				logId: item.logId,
			};
		})

		const { stateLightBoxVisible } = this.state;
		this.setState({
			stateLightBoxVisible: !stateLightBoxVisible
		});
	}

	_closeLightBox () {
		this.lightBoxData.modalVisible = false;
		this.stateLightBoxData.modalVisible = false;
		const { lightBoxVisible, stateLightBoxData } = this.state;
		this.setState({
			lightBoxVisible: !lightBoxVisible,
			stateLightBoxData: !stateLightBoxData,
		});
	}

	getPayTypeName (payType) {
		if ('3' === payType) {
			return '货到';
		}
		else if ('4' === payType) {
			return '签订';
		}
		else if ('5' === payType) {
			return '票到';
		} else {
			return '签订';
		}
	}

	render () {
		let { data, basicInfoOnoff, basicInfoAnim, itemAnim, itemOnoff, itemOnoffValue } = this.state;
		let { bizStaffName, priceType, currencyName, outOrderPayMethodList, companyName, orderId, payTypeName, quantity, prepayRate, payStyleName, payExpireDays,
			deliveryExpireDays, payType, periodType, baseDateSettleName, lostRender, orderItemList, oppoOrderId,
			creditInfo, totalOrderAmt, beyondCreditAmt, currency, orderType } = data;
		const approvalView = this.getApprovalView(totalOrderAmt, beyondCreditAmt, CURRENCY.getUnit(currency), periodType);
		let basicCss = basicInfoOnoff ? { height: basicInfoAnim } : null;
		return (
			<View style={styles.container}>
				<View style={styles.emptyBg}>
				</View>

				<TouchableOpacity style={styles.paiziBox} onPress={() => { this._didPressShowStateLightBox(orderId) }} activeOpacity={1}>
					<Image style={styles.paiziBg} source={require('../../../../imgs/apply/topTitle.png')} />
					<View style={styles.paizi}>
						<Text style={styles.topLeft}>{this.auditResultName}</Text>
						<Text style={styles.topRight}>{companyName ? companyName : this.companyName}</Text>
					</View>
				</TouchableOpacity>

				<ScrollView style={{ paddingTop: 10 * scale }}>
					<View style={styles.itemBox}>
						<Animated.View style={[basicCss, styles.animateBg]}>
							<Text style={styles.itemTitle}>基本信息</Text>
							<SpaceBetween fontLeft={{ title: '订单编号' }} fontRight={{ title: orderId }} />
							<SpaceBetween fontLeft={{ title: orderType && orderType === 'S' ? '客户' : '供应商' }} fontRight={{ title: companyName }} />
							<SpaceBetween fontLeft={{ title: '申请人' }} fontRight={{ title: bizStaffName }} />
							<SpaceBetween fontLeft={{ title: orderType && orderType === 'S' ? '收款类型' : '付款类型' }} fontRight={{ title: payTypeName }} />
							{
								CREDIT_TYPES[orderType] && CREDIT_TYPES[orderType][payType] && periodType !== 'L' ?
									<Text style={styles.credit}>授信可用金额 {CURRENCY.getUnit(currency).label + MethodUtil.toThousands((creditInfo && creditInfo.limitAmount || 0)) + CURRENCY.getUnit(currency).text}  已用额度 {CURRENCY.getUnit(currency).label + MethodUtil.toThousands((creditInfo && creditInfo.usedAmount || 0)) + CURRENCY.getUnit(currency).text}  有效期至{creditInfo && creditInfo.creditEndDate}</Text>
									: null
							}
							{prepayRate ? <SpaceBetween fontLeft={{ title: '定金比例' }} fontRight={{ title: prepayRate + '%' }} /> : null}
							{payExpireDays ? <SpaceBetween fontLeft={{ title: this.getPayTypeName(payType) }} fontRight={{ title: payExpireDays + '天内' + (orderType === 'S' ? '收' : '付') + '款' }} /> : null}
							{deliveryExpireDays && '4' === payType ? <SpaceBetween fontLeft={{ title: '款到' }} fontRight={{ title: deliveryExpireDays + '天内交货' }} /> : null}
							{payStyleName ? <SpaceBetween fontLeft={{ title: orderType === 'S' ? '收款方式' : '付款方式' }} fontRight={{ title: payStyleName }} /> : null}
							{outOrderPayMethodList ? outOrderPayMethodList.map((payItem, i) => {
								return (
									<View>
										<SpaceBetween fontLeft={{ title: orderType === 'S' ? '收款方式' : '付款方式' }} fontRight={{ title: payItem.payMethodName }} />
										<SpaceBetween fontLeft={{ title: orderType === 'S' ? '收款比例' : '付款比例' }} fontRight={{ title: MethodUtil.countObj.multiply(payItem.prepayRate, 100) + '%' }} />
									</View>
								)
							}) : null}
							<SpaceBetween fontLeft={{ title: '币种' }} fontRight={{ title: currencyName || '人民币' }} />
							{baseDateSettleName ? <SpaceBetween fontLeft={{ title: '结算基准日期' }} fontRight={{ title: baseDateSettleName }} /> : null}
						</Animated.View>
						<MorePage text={basicInfoOnoff ? this.animateData.basic.start.basicInfoText : this.animateData.basic.end.basicInfoText} onPressFn={() => { this._onPressFn(this.animateData.basic, basicInfoOnoff, 'basicInfo', basicInfoAnim) }} />
					</View>

					{
						orderItemList && orderItemList.length > 0 ? (
							orderItemList.map((item, index) => {
								//给循环的每一个item设定动画属性值
								this.animateData.basic.start.itemValue[index] = this.animateData.basic.start.itemValue[index] || 100;
								this.animateData.basic.end.itemValue[index] = this.animateData.basic.end.itemValue[index] || 220;
								itemAnim[index] = itemAnim[index] ? itemAnim[index] : new Animated.Value(this.animateData.basic.start.itemValue[index]);

								return (
									<View key={index} style={[styles.itemBox, styles.borders]}>
										<View style={[styles.animateBg]}>
											<Text style={styles.itemTitle}>{item.goodsName}</Text>
											<SpaceBetween fontLeft={{ title: '数量' }} fontRight={{ title: item.quantity + item.uomName }} />
											<SpaceBetween fontLeft={{ title: priceType == '2' ? '暂定价' : '单价' }} fontRight={{ title: CURRENCY.getUnit(currency).label + MethodUtil.toThousands(item.price) + CURRENCY.getUnit(currency).text + '/' + item.uomName }} />
											{item.priceFormulaDesc ? <SpaceBetween fontLeft={{ title: '计价公式' }} fontRight={{ title: item.priceFormulaDesc }} /> : null}
											{item.udPrice ? <SpaceBetween fontLeft={{ title: '升贴水' }} fontRight={{ title: (item.udPrice >= 0 ? '+' : '') + item.udPrice + CURRENCY.getUnit(currency).text + '/' + item.uomName }} /> : null}
											<SpaceBetween fontLeft={{ title: '总价' }} fontRight={{ title: CURRENCY.getUnit(currency).label + MethodUtil.toThousands(item.amount) + CURRENCY.getUnit(currency).text, style: { color: style.color.pink } }} />
										</View>
										{/* <MorePage text={itemOnoffValue[index] || '展开更多'} onPressFn={() => { this._onPressFn(this.animateData.basic, itemOnoff[index], 'item', itemAnim[index], index) }} /> */}
									</View>
								)
							})
						) : null
					}
					<StateLightBox  {...this.stateLightBoxData} textStyle={{ marginLeft: 15 * scale, marginRight: 5 * scale }} />
					<LightBox {...this.lightBoxData} />
				</ScrollView>

				{approvalView}
				<RefuseModal visible={this.state.refuseModalVisible} btnPress={async (remark) => {
					this.remark = remark;
					this._fetchApproval('0');
				}} bgPress={() => {
					this.setState({
						refuseModalVisible: false,
					});
				}} />
				{
					this.state.loaded ?
						<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
							<PageStatusIndex status='loading' />
						</View>
						: null
				}

			</View >
		)
	}
}
const styles = StyleSheet.create({
	ocrWrap: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, 0)',
		justifyContent: 'center',
		alignItems: 'center',
	},
	loadedCell: {
		width: 75 * scale,
		height: 75 * scale,
		backgroundColor: 'rgba(0, 0, 0, .5)',
		borderRadius: 7,
		justifyContent: 'center',
		alignItems: 'center',
	},
	container: {
		flex: 1,
		backgroundColor: style.color.white,
	},
	emptyBg: {
		height: 39 * scale,
		backgroundColor: style.color.themeColor,
		marginBottom: 13 * scale,
	},
	paiziBox: {
		zIndex: 99,
		width: 361 * scale,  // 726
		height: 60 * scale,
		position: 'absolute',
		left: 7 * scale,
		top: 8 * scale
	},
	paizi: {
		flexDirection: 'row',
		height: 48 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
		paddingTop: 10 * scale
	},
	paiziBg: {
		width: 361 * scale,
		position: 'absolute',
	},
	topLeft: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
	},
	topRight: {
		fontSize: 13 * scale,
		color: '#222',
	},
	itemBox: {
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		marginBottom: 13 * scale
	},
	itemTitle: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
		height: 20 * scale,
		lineHeight: 20 * scale,
		marginTop: 12 * scale,
		marginBottom: 12 * scale
	},
	borders: {
		borderTopWidth: 12 * scale,
		borderStyle: 'solid',
		borderTopColor: style.color.dullGrey,
	},
	infoBlue: {
		width: '100%',
		backgroundColor: style.color.infoBlue,
		borderRadius: 4 * scale,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 8 * scale,
		paddingRight: 8 * scale,
		marginTop: 5 * scale,
		marginBottom: 5 * scale
	},
	infoText: {
		fontSize: 12 * scale,
		color: '#2F7BFF'
	},
	newPrice: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		position: 'relative',
		height: 40 * scale
	},
	newPriceBg: {
		height: 24 * scale,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#EDF3FF',
		marginBottom: 15 * scale,
		borderRadius: 12 * scale,
		position: 'absolute',
		top: 0,
		left: 0
	},
	priceTitle: {
		fontSize: 10 * scale,
		color: '#222',
	},
	price: {
		color: style.color.taps,
		fontSize: 13 * scale
	},
	lotBox: {
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.border,
		height: 60 * scale,
		flexDirection: 'row',
		alignItems: 'center'
	},
	lotItem: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	lotText: {
		width: '50%',
		height: 20 * scale,
		fontSize: 18 * scale,
		color: style.color.dark,
		marginLeft: 15 * scale,
		borderRightWidth: 2 * scale,
		borderStyle: 'solid',
		borderRightColor: style.color.border,
	},
	animateBg: {
		backgroundColor: style.color.white
	},
	credit: {
		fontSize: 13 * scale,
		color: '#f86765',
		padding: 4 * scale
	},
	arrowLeft: {
		width: 6 * scale,
		height: 11 * scale,
	},
})